<script lang="ts" setup>
import { ref } from 'vue'
import type { FormProps } from 'element-plus'
import type { UploadProps, UploadUserFile } from 'element-plus'
import { ElMessage, ElMessageBox, ElLoading } from 'element-plus'
import axios from 'axios';

const formRef = ref()
const uploadRef = ref();
const formLabelAlign = ref({
    user_name: "myy@addcn.com|Maochengliang@96",
    num: '',
    platform: '',
    dir: "",
    project: ""
})

const userNameOptions = ref([
    {
        value: "myy@addcn.com|Maochengliang@96",
        label: "毛有有",
    },
    {
        value: "xuwanle@addcn.com|Xuwanle2604-+",
        label: "许万乐",
    },
    {
        value: "13480106073|liuqian2010.",
        label: "刘倩",
    },
    {
        value: "liangjinsong@addcn.com|aa123456.",
        label: "梁锦松",
    },

])
const options = ref([
    {
        value: "PC",
        label: "PC",
    },
    {
        value: "Touch",
        label: "Touch",
    },
    {
        value: "Android",
        label: "Android",
    },
    {
        value: "IOS",
        label: "IOS",
    }
])

const project_options = ref(
    [
        {
            value: "63835346",
            label: "T5"
        },
        {
            value: "51931447",
            label: "T5 Engineering"
        }
    ]
)

const handleRemove: UploadProps['onRemove'] = (file, uploadFiles) => {
    console.log(file, uploadFiles)
}

const handlePreview: UploadProps['onPreview'] = (uploadFile) => {
    console.log(uploadFile)
}

const handleExceed: UploadProps['onExceed'] = (files, uploadFiles) => {
    ElMessage.warning(
        `最多上传1个文件, 你已上传了 ${files.length} 个文件`
    )
}

const beforeRemove: UploadProps['beforeRemove'] = (uploadFile, uploadFiles) => {
    return ElMessageBox.confirm(
        `确认要删除 ${uploadFile.name} ?`
    ).then(
        () => true,
        () => false
    )
}

const fileList = ref<UploadUserFile[]>([

])

const importCase = async () => {
    const loading = ElLoading.service({
        lock: true,
        text: 'Loading',
        background: 'rgba(0, 0, 0, 0.7)',
    })
    const formData = new FormData();

    // 添加 fileList 中的所有文件到 FormData
    fileList.value.forEach((fileItem) => {
        if (fileItem.raw) {
            formData.append('fileList', fileItem.raw); // 'files' 是后端接收的字段名
        }
    });

    formData.append('num', formLabelAlign.value.num);
    formData.append('platform', formLabelAlign.value.platform);
    formData.append('dir', formLabelAlign.value.dir);
    formData.append('project', formLabelAlign.value.project);
    formData.append('user_name', formLabelAlign.value.user_name);
    axios.post("import_case/", formData, {
        headers: {
            'Content-Type': 'multipart/form-data',
        },
    })
        .then((res: any) => {

            loading.close()
            ElMessage({
                message: res.data.message,
                type: 'success',
                showClose: true,
            })

            if (uploadRef.value) {
                uploadRef.value.clearFiles();
            }


        })
        .catch((error: any) => {
            if (uploadRef.value) {
                uploadRef.value.clearFiles();
            }
            loading.close()
            ElMessage({
                message: '导入失败，请确认用例格式有无问题',
                type: 'error',
            })
            console.error(error);
        });
}

const downXmind = async () => {
    const loading = ElLoading.service({
        lock: true,
        text: 'Loading',
        background: 'rgba(0, 0, 0, 0.7)',
    })

    await axios.post("downloadXmindFile/", {}, { responseType: 'blob' })
        .then((res) => {
            // 使用 Blob 创建下载 URL
            const downloadUrl = window.URL.createObjectURL(new Blob([res.data]));
            const link = document.createElement('a');
            link.href = downloadUrl;
            link.setAttribute('download', `Xmind测试用例模板.xmind`); // 设置下载文件名
            link.style.display = 'none'; // 隐藏链接
            document.body.appendChild(link); // 将链接添加到文档中
            link.click(); // 模拟点击
            document.body.removeChild(link); // 移除链接
            window.URL.revokeObjectURL(downloadUrl); // 清理URL对象

            loading.close()
            ElMessage({
                message: "下载成功~~~",
                type: 'success',
                showClose: true,
            })
        })
        .catch((error) => {
            loading.close()
            ElMessage({
                message: '下载失败，请重试看看',
                type: 'error',
            })
            console.error(error);
        });
}
</script>


<template>
    <el-card class="box-card">
        <template #header>
            <div class="card-header">
                <span style="color: #ffffff;">591测试用例转换与导入TAPD平台</span>
            </div>
        </template>

        <el-button type="success" @click="downXmind">下载xmind示例模板</el-button>

        <!-- <el-col :span="8" :offset="16">
            <div style="display: flex; flex-direction: row !important; justify-content: flex-end !important; align-items: flex-end !important; align-content: flex-end !important;">
                <el-select>
                </el-select>
            </div>
        </el-col> -->


        <el-row style="margin-top: 30px;">
            <el-col :span="8" :offset="8">
                <el-form label-width="200px" ref="formRef" :model="formLabelAlign" style="max-width: 100%`">

                    <el-form-item label="选择需要导入的用户：">
                        <el-select v-model="formLabelAlign.user_name" class="m-2" placeholder="请选择用户"
                            style="width: 400px;">
                            <el-option v-for="item in userNameOptions" :key="item.value" :label="item.label"
                                :value="item.value"></el-option>
                        </el-select>
                    </el-form-item>



                    <el-form-item label="项目：">
                        <!-- <el-input v-model="formLabelAlign.res_type" /> -->
                        <el-select v-model="formLabelAlign.project" class="m-2" placeholder="请选择需要导入的项目"
                            style="width: 400px;">
                            <el-option v-for="item in project_options" :key="item.value" :label="item.label"
                                :value="item.value"></el-option>
                        </el-select>
                    </el-form-item>


                    <el-form-item label="用例目录：">
                        <el-input v-model="formLabelAlign.dir" placeholder="如：行情业务-版本1需求测试用例-PC" />
                    </el-form-item>
                    <el-form-item label="需求编号：">
                        <el-input v-model="formLabelAlign.num" placeholder="如：1163835346001048688" />
                    </el-form-item>
                    <el-form-item label="用例平台：">
                        <!-- <el-input v-model="formLabelAlign.res_type" /> -->
                        <el-select v-model="formLabelAlign.platform" class="m-2" placeholder="请选择用例平台"
                            style="width: 400px;" multiple>
                            <el-option v-for="item in options" :key="item.value" :label="item.label"
                                :value="item.value"></el-option>
                        </el-select>
                    </el-form-item>

                    <el-form-item label="选择xmind：">
                        <el-upload :auto-upload="false" class="upload-demo" multiple :on-preview="handlePreview"
                            :on-remove="handleRemove" ref="uploadRef" :before-remove="beforeRemove"
                            v-model:file-list="fileList" :limit="1" accept=".xmind" :on-exceed="handleExceed">
                            <el-button type="primary">选择文件</el-button>
                            <!-- <template #tip>
                                <div class="el-upload__tip">
                                    jpg/png files with a size less than 500KB.
                                </div>
                            </template> -->
                        </el-upload>
                    </el-form-item>
                    <el-form-item>
                        <el-button style="width: 400px;" type="success" @click.prevent="importCase">导入用例</el-button>
                    </el-form-item>
                </el-form>
            </el-col>
        </el-row>





    </el-card>
</template>


<!-- <style scoped>
/* 调整进度条样式 */


.el-upload-list__item {
    width: 800px;
}
</style> -->